import {
  myRequesy
} from '../../request/api'
import {
  useShowToast
} from '../../commons/index'
import paltter from '../../platter/carc'
// 在页面中定义插屏广告
let interstitialAd = null
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banner: null, //横幅
    title: "", //标题
    description: [], //活动列表
    is_description: false, //是否展示表单
    fromList: [], //题目列表
    is_start: false, //是否收集
    has_record: false, //是否提交
    is_modify: false, //是否可以修改
    formId: 0, // 表单id
    isCheck: false, //选中,
    isModal: false, //不可修改提示 
    shareShow: false, //控制海报弹窗
    isPoster: false, //控制海报遮罩层
    is_admin: false,
    is_auth: true,
    tid: 0
  },

  timer: null, //防抖
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-14b074ddbd370e0e'
      })
      interstitialAd.onLoad(() => {})
      interstitialAd.onError((err) => {})
      interstitialAd.onClose(() => {})
    }
    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }



    this.setData({
      formId: options.scene ? options.scene : options.id,
      is_admin: options.is_admin ? true : false,
      tid: parseInt(options.tid) || 0
    })


    this.getFromData()

  },

  // 获取表单数据
  getFromData() {
    let that = this
    myRequesy({
      url: that.data.is_admin ? 'admin/activity-detail' : 'tianxie',
      data: {
        a_id: that.data.formId
      }
    }).then(res => {
      if (res.code === 0) {
        let {
          description,
          banner,
          is_description,
          title,
          question_list,
          conclusion,
          is_start,
          has_record,
          is_modify,
          ret_type,
          ret_appid,
          ret_page,
          is_conclusion,
          ret_url
        } = res.data
        let succData = {
          ret_type,
          ret_appid,
          ret_page,
          ret_url,
          conclusion,
          is_conclusion
        }
        that.setData({
          title,
          description,
          banner,
          is_description,
          fromList: question_list,
          is_start,
          has_record,
          is_modify,
          succData
        })
        this.getChecked()
      }

    })
  },

  // 判断必选是否选中
  getChecked() {
    let {
      fromList
    } = this.data
    if (fromList.length) {
      this.setData({
        isCheck: fromList.filter(item => item.is_required).every(item => item.content)
      })
    }

  },


  //月日选择器 滚动时
  /*   bindMultiPickerColumnChange(e) {
      let {
        multiArray,
        multiIndex
      } = this.data
      multiIndex[e.detail.column] = e.detail.value;
      let day = []
      for (let i = 1; i <= 31; i++) {
        day.push(i < 10 ? '0' + i : i)
      }
      if (e.detail.column === 0) {
        if (multiIndex[0] === 1) {
          multiArray[1] = day.splice(0, 29)
        } else if (multiIndex[0] === 3 || multiIndex[0] === 5 || multiIndex[0] === 8 || multiIndex[0] === 10) {
          multiArray[1] = day.splice(0, 30)
        } else {
          multiArray[1] = day
        }
      }
      this.setData(multiArray)
    },

    //月日选择器 确定
    bindMultiPickerChange(e) {
      this.setData({
        multiIndex: e.detail.value
      })

    }, */



  // 选择器 函数
  handleSelector(e) {
    let {
      detail,
      currentTarget
    } = e.detail
    let {
      index,
      type
    } = currentTarget.dataset
    let {
      fromList
    } = this.data
    if (type == 2) {
      fromList[index].content = detail.value.join('-')
    } else {
      fromList[index].content = detail.value
    }
    this.setData({
      fromList
    })
    this.getChecked()

  },



  // 文本题输入 函数
  headleInput(e) {
    let {
      index
    } = e.currentTarget.dataset
    let {
      fromList
    } = this.data
    if (fromList[index].value_len == 0 || e.detail.value.length <= fromList[index].value_len) {
      fromList[index].content = e.detail.value
    } else {
      useShowToast(`最多可输入${fromList[index].value_len}个`)
    }
    this.setData({
      fromList
    })
    this.getChecked()
  },


  // 附件题上传 函数
  headleUpAccessory(e) {
    let that = this
    let {
      type,
      index
    } = e.detail
    let {
      fromList,
      is_modify,
      has_record,
      is_admin

    } = that.data
    if (!is_modify && has_record || is_admin) return
    if (type === 7) {
      wx.chooseMessageFile({
        count: 1,
        type: 'file',
        success(res) {
          if (fromList[index].size && res.tempFiles[0].size > (fromList[index].size * 1024 * 1024)) {
            useShowToast(`文件大小不能超过${fromList[index].size}M`)

          } else {
            wx.showLoading({
              title: '上传中....',
            })
            that.headleCheckout(res.tempFiles, index, type)
          }
        }
      })
    } else {
      wx.chooseMedia({
        count: 1,
        mediaType: type === 5 ? ['image'] : ['video'],
        success(res) {
          if (fromList[index].size && res.tempFiles[0].size > (fromList[index].size * 1024 * 1024)) {
            useShowToast(`文件大小不能超过${fromList[index].size}M`)
          } else {
            wx.showLoading({
              title: '上传中....',
            })
            that.headleCheckout(res.tempFiles, index, type)
          }
        }
      })
    }
  },


  //附件校验规则
  headleCheckout(data, activeIndex, type) {
    let that = this
    let filename = type === 7 ? data[0].path : data[0].tempFilePath
    let fileNames = filename.lastIndexOf("."); //取到文件名开始到最后一个点的长度
    let fileNameLength = filename.length; //取到文件名长度
    let fileFormat = filename.substring(fileNames + 1, fileNameLength); //截
    if (type === 5) {
      if (fileFormat === "jpg" || fileFormat === "png" || fileFormat === "jpeg") {
        that.headleUploadFile(data, activeIndex, type, )
      } else {
        useShowToast("文件格式错误")
        wx.hideLoading()
      }
    } else if (type === 6) {
      if (fileFormat === "mp4") {
        that.headleUploadFile(data, activeIndex, type, )
      } else {
        useShowToast("文件格式错误")
        wx.hideLoading()
      }
    } else if (type === 7) {
      that.headleUploadFile(data, activeIndex, type, )
    } else {
      useShowToast("文件格式错误")
      wx.hideLoading()
    }

  },

  //附件上传
  headleUploadFile(data, activeIndex, type) {
    let that = this
    let {
      fromList
    } = that.data
    wx.uploadFile({
      url: app.globalData.Url + 'upload-file',
      filePath: type === 7 ? data[0].path : data[0].tempFilePath,
      name: 'file	',
      header: {
        'Authorization': wx.getStorageSync('userInfo').token
      },
      success: function (res) {
        var data = JSON.parse(res.data);
        if (data.code === 0) {
          fromList[activeIndex].content = data.data.url
          that.setData({
            fromList
          })
          that.getChecked()
        }
        wx.hideLoading()
      },
    });
  },

  /*单选题
  headleCheck(e) {
    let {
      curr,
      index
    } = e.detail
    let {
      fromList,
      is_modify,
      has_record,
      is_admin
    } = this.data
    if (!is_modify && has_record || is_admin) return
    if (fromList[curr].option_list[index].is_select) {
      fromList[curr].option_list[index].is_select = false
      fromList[curr].content = ""
    } else {
      fromList[curr].option_list.forEach((item, i) => index === i ? item.is_select = true : item.is_select = false)
      fromList[curr].content = true
    }
    this.setData({
      fromList
    })
    this.getChecked()

  },*/


  //选择题
  headleAllCheck(e) {
    let {
      curr,
      index
    } = e.detail
    let {
      fromList,
      is_modify,
      has_record,
      is_admin
    } = this.data
    if (!is_modify && has_record || is_admin) return
    if (fromList[curr].is_multiple) {
      if (fromList[curr].option_list.filter(item => item.is_select).length < fromList[curr].select_num) {
        fromList[curr].option_list[index].is_select = !fromList[curr].option_list[index].is_select
      } else {
        if (fromList[curr].option_list[index].is_select) {
          fromList[curr].option_list[index].is_select = !fromList[curr].option_list[index].is_select
        } else {
          useShowToast(`最多可选${fromList[curr].select_num}个`)
        }
      }
      fromList[curr].content = fromList[curr].option_list.filter(item => item.is_select).length
    } else {
      if (fromList[curr].option_list[index].is_select) {
        fromList[curr].option_list[index].is_select = false
        fromList[curr].content = ""
      } else {
        fromList[curr].option_list.forEach((item, i) => index === i ? item.is_select = true : item.is_select = false)
        fromList[curr].content = true
      }
    }
    this.setData({
      fromList
    })

    this.getChecked()

  },




  //关闭提示框
  headleClose() {
    this.setData({
      isModal: false
    })
  },


  // 提交
  headleSubmit() {
    clearTimeout(this.timer)
    this.timer = setTimeout(() => {

      let {
        isCheck,
        fromList,
        formId,
        is_start,
        is_modify,
        has_record,
        succData,
        tid
      } = this.data

      if (!isCheck) {
        useShowToast("请填写必填项")
      } else if (!is_start) {
        useShowToast("暂停收集")
      } else if (!is_modify && has_record) {
        this.setData({
          isModal: true
        })
      } else {
        wx.showLoading({
          title: "提交中...",
          mask: true
        })
        myRequesy({
          url: 'add-record',
          method: 'POST',
          data: {
            a_id: parseInt(formId),
            question_list: fromList,
            tid
          }
        }).then(res => {
          wx.hideLoading()
          if (res.code === 0) {
            wx.redirectTo({
              url: '/pages/prosperity/prosperity?succData=' + encodeURIComponent(JSON.stringify(succData))
            })
          }
        })
      }
    }, 500)
  },


  // 打开分享弹窗
  headleShare() {
    this.setData({
      shareShow: true
    })
  },

  // 关闭分享弹窗
  headleCloseShare() {
    this.setData({
      shareShow: false
    })
  },


  /* 海报区域*********************************************************************************************************** */

  // 海报
  headlePoster() {
    let that = this
    let {
      banner,
      title,
      formId
    } = that.data
    let car = new paltter().palette()
    let userInfo = wx.getStorageSync('userInfo')
    car.views[1].url = userInfo.avatarUrl
    car.views[2].text = userInfo.nickName
    car.views[3].url = banner
    car.views[4].text = title
    myRequesy({
      url: 'get-qrcode',
      data: {
        a_id: formId
      }
    }).then(res => {
      if (res.code === 0) {
        car.views[5].url = res.data.qrcode
        that.setData({
          template: car,
          isPoster: true,
          shareShow: false
        })
      }
    })
  },

  // 保存
  saveImg() {
    this.saveImage()
  },

  // 海报
  onImgOK(e) {
    var that = this
    var imagePath = e.detail.path;
    that.setData({
      imagePath: imagePath
    })
  },

  // 保存海报
  saveImage() {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success: (res) => {
        that.setData({
          poster_hidden: true,
          isPoster: false
        })
        wx.showToast({
          title: '已保存到相册',
        })
        // setTimeout(() => {
        //   wx.navigateBack()
        // }, 1000)
      },
      fail() {
        wx.showModal({
          title: '保存失败！',
          content: '请检查相册访问是否授权',
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(res) {}
              })
            } else if (res.cancel) {}
          }
        })
      }
    });
  },

  //关闭遮罩层
  headleMask() {
    this.setData({
      isPoster: false
    })
  },

  // 登录授权
  getLogin() {
    let that = this
    wx.getUserProfile({
      desc: '获取您的用户名和头像',
      success(res1) {
        wx.login({
          success(res2) {
            let userData = {
              code: res2.code,
              nickName: res1.userInfo.nickName,
              avatarUrl: res1.userInfo.avatarUrl
            }
            myRequesy({
              url: 'Login',
              data: userData,
              method: "POST",
            }).then(res => {
              if (res.code === 0) {
                wx.setStorage({
                  data: res.data,
                  key: 'userInfo',
                  success() {
                    that.setData({
                      is_auth: false
                    })
                    that.getFromData()
                  }
                })
              }
            })
          }
        })
      }
    })
  },

  handleLogin() {
    this.getLogin()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        is_auth: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let {
      formId,
      title,
      banner
    } = this.data
    if (res.from === 'button') {
      return {
        title: title,
        imageUrl: banner,
        path: "/pages/form/form?id=" + formId
      }
    }
  }
})